<template>
  <div class="data-table">
    <!-- 工具栏 -->
    <div class="toolbar" v-if="showToolbar">
      <div class="toolbar-left">
        <slot name="toolbar-left">
          <el-input
            v-if="searchable"
            v-model="searchQuery"
            :placeholder="searchPlaceholder"
            clearable
            @input="handleSearch"
            @clear="handleSearchClear"
            class="search-input"
            style="width: 280px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </slot>
      </div>
      <div class="toolbar-right">
        <slot name="toolbar-right">
          <el-button
            v-if="batchDeleteEnabled && hasSelection"
            type="danger"
            @click="handleBatchDelete"
            class="batch-delete-btn"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selection.length }})
          </el-button>
          <el-button
            v-if="refreshEnabled"
            @click="refresh"
            class="refresh-btn"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </slot>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        ref="tableRef"
        :data="data"
        v-loading="loading"
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        v-bind="$attrs"
      >
        <!-- 选择列 -->
        <el-table-column
          v-if="selectable"
          type="selection"
          width="50"
        />
        
        <!-- 序号列 -->
        <el-table-column
          v-if="showIndex"
          type="index"
          label="序号"
          width="60"
          :index="getIndex"
        />

        <!-- 动态列 -->
        <template v-for="column in columns" :key="column.prop">
          <el-table-column
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :min-width="column.minWidth"
            :align="column.align || 'left'"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.showOverflowTooltip !== false"
          >
            <template #default="scope" v-if="column.slot">
              <slot :name="column.slot" :row="scope.row" :column="scope.column" :index="scope.$index" />
            </template>
            <template #default="scope" v-else-if="column.formatter">
              <span v-html="column.formatter(scope.row, scope.column, scope.row[column.prop])"></span>
            </template>
          </el-table-column>
        </template>

        <!-- 操作列 -->
        <el-table-column
          v-if="$slots.actions"
          label="操作"
          :width="actionWidth"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <slot name="actions" :row="scope.row" :index="scope.$index" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="showPagination && pagination.total > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="pageSizes"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete, Refresh } from '@element-plus/icons-vue'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  align?: 'left' | 'center' | 'right'
  sortable?: boolean
  showOverflowTooltip?: boolean
  slot?: string
  formatter?: (row: any, column: any, cellValue: any) => string
}

export interface TablePagination {
  page: number
  pageSize: number
  total: number
}

interface Props {
  data: any[]
  columns: TableColumn[]
  loading?: boolean
  pagination?: TablePagination
  searchable?: boolean
  searchPlaceholder?: string
  selectable?: boolean
  showIndex?: boolean
  showToolbar?: boolean
  showPagination?: boolean
  batchDeleteEnabled?: boolean
  refreshEnabled?: boolean
  tableHeight?: string | number
  actionWidth?: string | number
  pageSizes?: number[]
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  searchable: true,
  searchPlaceholder: '请输入搜索关键词...',
  selectable: true,
  showIndex: false,
  showToolbar: true,
  showPagination: true,
  batchDeleteEnabled: true,
  refreshEnabled: true,
  tableHeight: 'auto',
  actionWidth: 180,
  pageSizes: () => [10, 20, 50, 100]
})

const emit = defineEmits<{
  search: [query: string]
  refresh: []
  selectionChange: [selection: any[]]
  sortChange: [sort: { prop: string; order: string }]
  pageChange: [page: number]
  pageSizeChange: [size: number]
  batchDelete: [selection: any[]]
}>()

// 响应式数据
const tableRef = ref()
const searchQuery = ref('')
const selection = ref<any[]>([])

// 计算属性
const hasSelection = computed(() => selection.value.length > 0)

// 获取序号
const getIndex = (index: number) => {
  if (props.pagination) {
    return (props.pagination.page - 1) * props.pagination.pageSize + index + 1
  }
  return index + 1
}

// 事件处理
const handleSearch = () => {
  emit('search', searchQuery.value)
}

const handleSearchClear = () => {
  searchQuery.value = ''
  emit('search', '')
}

const handleSelectionChange = (newSelection: any[]) => {
  selection.value = newSelection
  emit('selectionChange', newSelection)
}

const handleSortChange = (sort: any) => {
  emit('sortChange', {
    prop: sort.prop,
    order: sort.order
  })
}

const handleCurrentChange = (page: number) => {
  emit('pageChange', page)
}

const handleSizeChange = (size: number) => {
  emit('pageSizeChange', size)
}

const handleBatchDelete = async () => {
  if (selection.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selection.value.length} 个项目吗？`,
      '确认批量删除',
      { type: 'warning' }
    )
    
    emit('batchDelete', selection.value)
  } catch {
    // 用户取消
  }
}

const refresh = () => {
  emit('refresh')
}

// 清空选择
const clearSelection = () => {
  tableRef.value?.clearSelection()
}

// 暴露方法
defineExpose({
  clearSelection,
  refresh
})
</script>

<style scoped>
.data-table {
  background: var(--el-bg-color);
  border-radius: 8px;
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--el-bg-color-page);
  border-bottom: 1px solid var(--el-border-color-light);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-container {
  min-height: 200px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: var(--el-bg-color-page);
  border-top: 1px solid var(--el-border-color-light);
}

.search-input {
  --el-input-border-radius: 6px;
}

.batch-delete-btn {
  --el-button-bg-color: var(--el-color-danger);
  --el-button-border-color: var(--el-color-danger);
}

.refresh-btn {
  --el-button-bg-color: var(--el-color-info);
  --el-button-border-color: var(--el-color-info);
}
</style>
